package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时人物类， 定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时任务的订单
     * 每分钟触发一次: 0 * * * * ?
     * 每五分钟触发一次：0 0/5 * * * ?
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    //@Scheduled(cron = "1/5 * * * * ?")  //测试每隔5s执行一次
    public void processTimeOutOrder() {
        log.info("定时处理超时任务：{}", LocalDateTime.now());

        // select * from orders where status = ? and order_time < LocalDateTime -15 min
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);

        if (ordersList != null && !ordersList.isEmpty()) {
            //遍历集合，将订单的状态修改为“已取消”
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("超过支付时间，订单已自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }


    /**
     * 处理一直处于派送中的订单
     * 每天凌晨三点自动完成
     */
    @Scheduled(cron = "0 0 3 * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")  //测试每隔5s执行一次
    public void processDeliveryOrder() {
        log.info("定时处理派送中的订单：{}", LocalDateTime.now());

        // 当前时间前去3小时，就是处理前一天的所有的派送中的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-300);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if (ordersList != null && !ordersList.isEmpty()) {
            //遍历集合，将订单的状态修改为“已完成”
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }

}
